<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import MD5 from 'crypto-js/md5';
import { useAntdForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { getVerificationCodeApi } from '@/service/api/businessApi';

defineOptions({
  name: 'PwdLogin'
});

const authStore = useAuthStore();
const { formRef, validate } = useAntdForm();

interface FormModel {
  userName: string;
  password: string;
  captcha: string;
}

const model: FormModel = reactive({
  userName: '',
  password: '',
  captcha: ''
});

const rules = computed(() => {
  return {
    userName: [
      {
        required: true,
        message: '请输入用户名'
      }
    ],
    password: [
      {
        required: true,
        message: '请输入密码'
      }
    ],
    captcha: [
      {
        required: true,
        message: '请输入验证码'
      }
    ]
  };
});
const randomCode = ref(new Date().valueOf());

async function handleSubmit() {
  await validate();
  await authStore.login({
    loginCode: model.userName,
    password: MD5(model.password).toString(),
    captcha: model.captcha,
    randomCode: randomCode.value,
    loginType: 2
  });
}

/* region ====== 获取验证码 start */
const captchaImg = ref(getVerificationCodeApi(randomCode.value));

const refreshCaptcha = () => {
  randomCode.value = new Date().valueOf();
  captchaImg.value = getVerificationCodeApi(randomCode.value);
};
/* endregion === 获取验证码 end */

/* region ====== 生命周期 start */
onMounted(() => {});
/* endregion === 生命周期 end */
</script>

<template>
  <AForm ref="formRef" :model="model" :rules="rules">
    <AFormItem name="userName">
      <AInput class="my-input" v-model:value="model.userName" size="large" placeholder="请输入用户名" />
    </AFormItem>
    <AFormItem name="password">
      <AInputPassword class="my-input" v-model:value="model.password" size="large" placeholder="请输入密码" />
    </AFormItem>
    <AFormItem name="captcha">
      <div class="flex gap-6px">
        <AInput class="my-input" v-model:value="model.captcha" size="large" placeholder="请输入验证码" />
        <img class="h-40px" :src="captchaImg" @click="refreshCaptcha" />
      </div>
    </AFormItem>
    <ASpace direction="vertical" size="large" class="w-full mt-50px">
      <AButton
        style="background: #1960BF; border-radius: 4px"
        type="primary"
        block
        size="large"
        :loading="authStore.loginLoading"
        @click="handleSubmit"
      >
        确认
      </AButton>
    </ASpace>
  </AForm>
</template>

<style scoped lang="scss">
.my-input {
  background: #162C4F;
  border: none;
  border-radius: 4px;
  color: #fff;
  &::placeholder {
    color: #43638B;
  }
  :deep(.ant-input) {
    background: #162C4F;
    color: #fff;
    &::placeholder{
      color: #43638B;
    }
  }
  :deep(.ant-input-suffix svg) {
    color: #6E9DD8;
  }
}
</style>
